package com.btex.app.pager;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.btex.app.AuthenticationInformationAcitvity;
import com.btex.app.Config;
import com.btex.app.LanguageActivity;
import com.btex.app.OTCActivity;
import com.btex.app.OTCPaymentMethodsActivity;
import com.btex.app.R;
import com.btex.app.WebActivity;
import com.btex.app.entity.GetInfo;
import com.btex.app.entity.OTCUserInfo;
import com.btex.app.tools.AdminsDialog;
import com.btex.app.tools.CookieTool;
import com.btex.app.tools.LogUtil;
import com.btex.app.tools.MicroAVLIDialog;
import com.btex.app.tools.SharedPreferencesUtil;
import com.google.gson.Gson;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.lidroid.xutils.util.PreferencesCookieStore;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * Created by wcx on 16/3/16.
 */
public class FragmentAdmins extends BaseFragment implements View.OnClickListener {
    private static final String TAG = "FragmentAdmin";
    Unbinder unbinder;
    @BindView(R.id.fragment_myself_but_unlogin)
    Button mFragmentMyselfButUnlogin;
    //    fragment_language_setting
    @BindView(R.id.name)
    TextView mName;

    @BindView(R.id.fragment_myself_c2c)
    LinearLayout fragment_myself_c2c;
    @BindView(R.id.fragment_myself_c2c_add)
    LinearLayout fragment_myself_c2c_add;

    @BindView(R.id.fragment_myself_c2c_view)
    View fragment_myself_c2c_view;

    @BindView(R.id.fragment_myself_c2c_add_view)
    View fragment_myself_c2c_add_view;

    @BindView(R.id.fragment_language_setting)
    TextView fragment_language_setting;

    @BindView(R.id.fragment_admins_swip)
    SwipeRefreshLayout fragment_admins_swip;


    private View view;
    private SharedPreferencesUtil sp;
    private PreferencesCookieStore cookieStore;
    private MicroAVLIDialog mMicroAVLIDialog;
    private MicroAVLIDialog mMicroAVLIDialog1;
//    sp.putString("check", "3");


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = View.inflate(getActivity(), R.layout.fragment_myself, null);
        unbinder = ButterKnife.bind(this, view);

        EventBus.getDefault().register(this);
        sp = SharedPreferencesUtil.getSharedPreferences(getActivity());
        cookieStore = CookieTool.getCookieStore(cxt, sp);
        String string = sp.getString(Config.KEY_USER_ACCOUNT, null);
        mMicroAVLIDialog1 = new MicroAVLIDialog(getActivity());

        boolean isEngilsh = sp.getBoolean("isEngilsh", false);

        String city_new = sp.getString("city_new", "0");
        if (city_new.equals("0")) {
            fragment_language_setting.setText("简体中文");
        } else if (city_new.equals("1")) {
            fragment_language_setting.setText("English");
        } else if (city_new.equals("2")) {

            fragment_language_setting.setText("日本語");

        } else {
            fragment_language_setting.setText("Espanhol");
        }

//        if (isEngilsh) {
//            fragment_language_setting.setText("English");
//        } else {
//            fragment_language_setting.setText("简体中文");
//        }

        if (!TextUtils.isEmpty(string)) {
            mName.setText(string);
        }


        return view;
    }


    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        if (fragment_admins_swip != null) {
            fragment_admins_swip.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
                @Override
                public void onRefresh() {
                    getUserInfo();
                }
            });
        }

    }

    @Override
    public void onResume() {
        super.onResume();


        String string = sp.getString(Config.KEY_USER_ACCOUNT, null);
        if (!TextUtils.isEmpty(string)) {
            mName.setText(string);
        }

        getUserInfo();

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @Override
    public void setData() {

    }

    @Override
    public void onClick(View v) {

    }


    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser) {
            getUserInfo();
        }
    }


    @OnClick({R.id.fragment_myself_safe, R.id.fragment_myself_autonyum, R.id.fragment_myself_zhuan_chu, R.id.fragment_myself_zhuan_ru, R.id.fragment_myself_cheng_jiao, R.id.fragment_myself_entrust, R.id.fragment_myself_setting, R.id.fragment_myself_but_unlogin, R.id.fragment_myself_wa_kuang, R.id.fragment_myself_wa_yao_qing, R.id.fragment_myself_c2c, R.id.fragment_myself_c2c_add})
    public void onViewClicked(View view) {
        switch (view.getId()) {
//            安全中心
            case R.id.fragment_myself_safe:

                sp.putString("check", "4");
                Intent intent = new Intent(getActivity(), WebActivity.class);
                intent.putExtra("web_url", Config.URL + "home/my_account");
                startActivity(intent);

                break;
//            实名认证
            case R.id.fragment_myself_autonyum:
                sp.putString("check", "4");

//                Intent ins = new Intent(cxt, WebActivity.class);
//                ins.putExtra("web_url", Config.URL + "home/safe_level");
//                startActivity(ins);

                Intent ins = new Intent(cxt, AuthenticationInformationAcitvity.class);
                ins.putExtra("web_url", Config.URL + "home/safe_level");
                startActivity(ins);


                break;
            case R.id.fragment_myself_zhuan_chu:
                sp.putString("check", "4");
//                getRen();

                getInfo();

//                Intent i = new Intent(getActivity(), WebActivity.class);
//                i.putExtra("web_url", Config.URL + "home/coins/withdraw/");
//                startActivity(i);

                break;
            case R.id.fragment_myself_zhuan_ru:
                sp.putString("check", "4");

                Intent in = new Intent(getActivity(), WebActivity.class);
                in.putExtra("web_url", Config.URL + "home/coins/deposit/");
                startActivity(in);

                break;
            case R.id.fragment_myself_cheng_jiao:
                sp.putString("check", "4");
                Intent inte = new Intent(cxt, WebActivity.class);
                inte.putExtra("web_url", Config.URL + "home/markets/trade/");
                startActivity(inte);

                break;
            case R.id.fragment_myself_entrust:
                sp.putString("check", "4");
                Intent intent1 = new Intent(cxt, WebActivity.class);
                intent1.putExtra("web_url", Config.URL + "home/markets/orders/");
                startActivity(intent1);

                break;
            case R.id.fragment_myself_setting:
                sp.putString("check", "4");
                Intent intent2 = new Intent(getActivity(), LanguageActivity.class);
                startActivity(intent2);

                break;
            case R.id.fragment_myself_but_unlogin:
                sp.putString("check", "4");
//                mFragmentMyselfButUnlogin.setClickable(false);
                mMicroAVLIDialog = new MicroAVLIDialog(getActivity());
                mMicroAVLIDialog.show();
                toLogout();

                break;

            case R.id.fragment_myself_wa_kuang:
                sp.putString("check", "4");
                Intent intentwa = new Intent(cxt, WebActivity.class);
                intentwa.putExtra("web_url", Config.URL + "pub/invite/help");
                startActivity(intentwa);

                break;

            case R.id.fragment_myself_wa_yao_qing:
                sp.putString("check", "4");
                Intent intentyao = new Intent(cxt, WebActivity.class);
                intentyao.putExtra("web_url", Config.URL + "home/dig_his_m");
                startActivity(intentyao);

                break;

            case R.id.fragment_myself_c2c:
                sp.putString("check", "4");
                Intent intentc = new Intent(getActivity(), OTCActivity.class);
                startActivity(intentc);
                break;

            case R.id.fragment_myself_c2c_add:
                sp.putString("check", "4");
                Intent intentadd = new Intent(getActivity(), OTCPaymentMethodsActivity.class);
                startActivity(intentadd);

                break;
        }


    }

    private void toLogout() {
        RequestParams params = new RequestParams();
        params.addHeader("myclient", "android");

        new HttpUtils().configCookieStore(cookieStore).send(HttpRequest.HttpMethod.GET, Config.URL_USER_LOGOUT, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                String result = responseInfo.result.toString();


                try {
                    JSONObject json = new JSONObject(result);
                    if ("1".equals(json.getString(Config.KEY_CODE))) {

                        mMicroAVLIDialog.dismiss();
                        sp.putBoolean(Config.KEY_IS_LOGIN, false);
                        sp.putString(Config.TOKEN, null);
                        EventBus.getDefault().post("loginsuccess");
//                        Intent i = new Intent(cxt, TabsActivity.class);
//                        getActivity().startActivity(i);
//                        getActivity().finish();

                    }
                } catch (JSONException e) {
                    LogUtil.e(TAG, e.toString());
                }
            }

            @Override
            public void onFailure(HttpException error, String msg) {

            }
        });
    }


//    CertificationOneActivity


    private void getInfo() {

        mMicroAVLIDialog1.show();
        SharedPreferencesUtil sp = SharedPreferencesUtil.getSharedPreferences(getActivity());
        PreferencesCookieStore cookieStore = CookieTool.getCookieStore(getActivity(), sp);
        int num = (int) ((Math.random() * 9 + 1) * 100000);
        RequestParams params = new RequestParams();
        params.addHeader("myclient", "android");
        new HttpUtils().configCookieStore(cookieStore).send(HttpRequest.HttpMethod.GET, Config.GET_MY_PROVE_INFO + "?rnd=" + String.valueOf(num), params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {

                mMicroAVLIDialog1.dismiss();
                String result = responseInfo.result;

                try {
                    JSONObject jsonObject = new JSONObject(result);
                    if ("1".equals(jsonObject.getString(Config.KEY_CODE))) {

                        GetInfo getInfo = new Gson().fromJson(result, GetInfo.class);
                        setGO(getInfo);

                    } else {

                    }
                } catch (JSONException e) {
                    e.printStackTrace();

                }

            }

            @Override
            public void onFailure(HttpException error, String msg) {


            }
        });


    }

    private void setGO(GetInfo getInfo) {


        if (getInfo.getData().getProve_level().equals("C2")) {

            if (getInfo.getData().getStatus().equals("1")) {

                Intent i = new Intent(getActivity(), WebActivity.class);
                i.putExtra("web_url", Config.URL + "home/coins/withdraw/");
                startActivity(i);

            } else {

                Intent i = new Intent(getActivity(), AuthenticationInformationAcitvity.class);
                startActivity(i);

            }
        } else {

            new AdminsDialog(getActivity(), getInfo.getData().getProve_level()).show();

        }

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void messag(String event) {

        if ("AdminsDialog".equals(event)) {

            getRen();


        }

        if ("loginsuccess".equals(event)) {
            if (mName != null) {
                String string = sp.getString(Config.KEY_USER_ACCOUNT, null);
                if (!TextUtils.isEmpty(string)) {
                    mName.setText(string);
                }

            }
        }


    }


    public void getRen() {


        mMicroAVLIDialog1.show();
        SharedPreferencesUtil sp = SharedPreferencesUtil.getSharedPreferences(getActivity());
        PreferencesCookieStore cookieStore = CookieTool.getCookieStore(getActivity(), sp);
        RequestParams params = new RequestParams();
        params.addHeader("myclient", "android");
        params.addBodyParameter("origin", "ali_rp");

        int num = (int) ((Math.random() * 9 + 1) * 100000);
        new HttpUtils().configCookieStore(cookieStore).send(HttpRequest.HttpMethod.POST, Config.USER_PROVE_ACTION + "?rnd=" + String.valueOf(num), params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {

                String result = responseInfo.result;
                mMicroAVLIDialog1.dismiss();

            }

            @Override
            public void onFailure(HttpException error, String msg) {


            }
        });


    }


    private void getUserInfo() {
        if (fragment_admins_swip != null) {
            fragment_admins_swip.setRefreshing(true);

        }
        PreferencesCookieStore cookieStore = CookieTool.getCookieStore(getActivity(), SharedPreferencesUtil.getSharedPreferences(getActivity()));
        RequestParams params = new RequestParams();
        params.addHeader("myclient", "android");
        new HttpUtils().configCookieStore(cookieStore).send(HttpRequest.HttpMethod.GET, Config.URL_MY_INFO, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                String reuslt = responseInfo.result.toString();

                if (fragment_admins_swip != null) {
                    fragment_admins_swip.setRefreshing(false);

                }

                try {
                    JSONObject jsonObject = new JSONObject(reuslt);

                    if (jsonObject.getString(Config.KEY_CODE).equals("1")) {
                        Gson gson = new Gson();
                        OTCUserInfo otcUserInfo = gson.fromJson(reuslt, OTCUserInfo.class);

                        boolean otc_is_show = otcUserInfo.getData().isOtc_is_show();


                        if (otc_is_show) {

                            Log.i("lenfjwleifjwoei", "1");

                            if (sp != null) {
                                boolean isEngilsh = sp.getBoolean("isEngilsh", false);
                                Log.i("lenfjwleifjwoei", "2");
                                if (isEngilsh) {
                                    Log.i("lenfjwleifjwoei", "3");
                                    fragment_myself_c2c.setVisibility(View.GONE);
                                    fragment_myself_c2c_add.setVisibility(View.GONE);
                                    fragment_myself_c2c_view.setVisibility(View.GONE);
                                    fragment_myself_c2c_add_view.setVisibility(View.GONE);
                                } else {
                                    Log.i("lenfjwleifjwoei", "4");
                                    fragment_myself_c2c.setVisibility(View.VISIBLE);
                                    fragment_myself_c2c_add.setVisibility(View.VISIBLE);
                                    fragment_myself_c2c_view.setVisibility(View.VISIBLE);
                                    fragment_myself_c2c_add_view.setVisibility(View.VISIBLE);
                                }
                            }

                        } else {
                            Log.i("lenfjwleifjwoei", "5");
                            fragment_myself_c2c.setVisibility(View.GONE);
                            fragment_myself_c2c_add.setVisibility(View.GONE);
                            fragment_myself_c2c_view.setVisibility(View.GONE);
                            fragment_myself_c2c_add_view.setVisibility(View.GONE);

                        }

                    }
                } catch (JSONException e) {
                    e.printStackTrace();

                }


            }

            @Override
            public void onFailure(HttpException error, String msg) {
            }
        });

    }


}
